import React, { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { Input } from "antd";
import Highcharts from "highcharts/highstock.src";
import HighchartsAccessibility from "highcharts/modules/accessibility.src";
import HighchartsAnnotationsAdvanced from "highcharts/modules/annotations-advanced.src";
import HighchartsStockTools from "highcharts/modules/stock-tools.src";
import HighchartsColumnrange from "highcharts/highcharts-more.src";
import "highcharts/css/annotations/popup.css";
import "highcharts/css/stocktools/gui.css";
import "./CandlestickChart.scss";

HighchartsAccessibility(Highcharts);
HighchartsAnnotationsAdvanced(Highcharts);
HighchartsStockTools(Highcharts);
HighchartsColumnrange(Highcharts);

const commonEnabled = {
  // boost: {
  //   useGPUTranslations: true,
  //   usePreallocated: true //缓存区分配，但是是试用性Api
  // },
  credits: {
    enabled: false //删除logo
  },
  time: {
    timezoneOffset: new Date().getTimezoneOffset() // 设置时区 东8 -480
  },
  stockTools: {
    gui: {
      enabled: false //左边画线工具
    }
  },
  rangeSelector: {
    //右上角有个日期区间
    enabled: false
  },
  plotOptions: {
    //自定义交互
    series: {
      animation: false,
      states: {
        //取消高亮
        hover: {
          enabled: false
        },
        inactive: {
          enabled: false
        }
      },
      marker: {
        enabled: undefined, //默认值
        enabledThreshold: Number.MAX_SAFE_INTEGER
      }
    },
    candlestick: {
      grouping: false
    },
    column: {
      minPointLength: 1 //柱子最小长度，为0的时候也有高度
    }
  },
  //自定义配置绘图工具
  bindings: {}
};


// 数据生成函数
const generateOHLCData = (days = 200): [number, number, number, number, number][] => {
  const data: [number, number, number, number, number][] = [];
  let date = new Date();
  date.setDate(date.getDate() - days);
  let price = 100;

  for (let i = 0; i < days; i++) {
    if (date.getDay() === 0 || date.getDay() === 6) {
      date.setDate(date.getDate() + 1);
      continue;
    }

    const timestamp = date.getTime();
    const open = +price.toFixed(2);
    const change = (Math.random() - 0.48) * 4;
    const close = +(open + change).toFixed(2);
    const high = +Math.max(open, close, open + Math.random() * 3).toFixed(2);
    const low = +Math.min(open, close, open - Math.random() * 3).toFixed(2);

    data.push([timestamp, open, high, low, close]);

    price = close;
    date.setDate(date.getDate() + 1);
  }

  return data;
};

// 时间范围类型
type TimeRange = "1M" | "3M" | "6M" | "1Y" | "ALL";

// 技术指标类型
type Indicator = "sma" | "ema" | "macd";

// 主题类型
type Theme = "light" | "dark";

// K线图组件
const CandlestickChart: React.FC = () => {
  const chartContainerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<Highcharts.Chart | null>(null);

  const [data, setData] = useState<[number, number, number, number, number][]>(generateOHLCData(365));
  const [timeRange, setTimeRange] = useState<TimeRange>("1Y");
  const [indicators, setIndicators] = useState<Indicator[]>(["sma", "ema", "macd"]);
  const [theme, setTheme] = useState<Theme>("light");
  const [isLoading, setIsLoading] = useState(false);

  const timeRanges: Record<TimeRange, number | null> = {
    "1M": 30,
    "3M": 90,
    "6M": 180,
    "1Y": 365,
    ALL: null
  };



  // 切换技术指标
  const toggleIndicator = (indicator: Indicator) => {
    setIndicators(prev => (prev.includes(indicator) ? prev.filter(i => i !== indicator) : [...prev, indicator]));
  };

  // 更改时间范围
  const changeTimeRange = (range: TimeRange) => {
    setIsLoading(true);
    setTimeRange(range);

    setTimeout(() => {
      const days = timeRanges[range];
      const newData = days ? generateOHLCData(days) : generateOHLCData(1000);
      setData(newData);
      setIsLoading(false);
    }, 500);
  };

  // 切换主题
  const toggleTheme = () => {
    setTheme(prev => (prev === "light" ? "dark" : "light"));
  };

  // 刷新数据
  const refreshData = () => {
    setIsLoading(true);

    setTimeout(() => {
      const newData = generateOHLCData(timeRanges[timeRange] || 365);
      setData(newData);
      setIsLoading(false);
    }, 800);
  };

  // 获取Highcharts配置
  const getChartOptions = useCallback(() => {
    const themeColors =
      theme === "light"
        ? {
            bg: "#FFFFFF",
            text: "#1E293B",
            grid: "#E2E8F0",
            axis: "#64748B",
            tooltipBg: "rgba(255, 255, 255, 0.8)",
            tooltipBorder: "#E2E8F0",
            navigatorMask: "rgba(59, 130, 246, 0.1)",
            scrollbar: {
              bar: "#E2E8F0",
              button: "#FFFFFF",
              track: "#F1F5F9"
            }
          }
        : {
            bg: "#1E293B",
            text: "#F8FAFC",
            grid: "#334155",
            axis: "#94A3B8",
            tooltipBg: "rgba(30, 41, 59, 0.8)",
            tooltipBorder: "#475569",
            navigatorMask: "rgba(59, 130, 246, 0.2)",
            scrollbar: {
              bar: "#334155",
              button: "#1E293B",
              track: "#1E293B"
            }
          };

    const baseOptions: Highcharts.Options = {
      ...commonEnabled,
      colors:
        theme === "light"
          ? [
              "#26A69A",
              "#EF5350",
              "#FFB74D",
              "#42A5F5",
              "#7E57C2",
              "#EC407A",
              "#5C6BC0",
              "#FF7043",
              "#66BB6A",
              "#26A69A"
            ]
          : [
              "#4DB6AC",
              "#EF5350",
              "#FFB74D",
              "#4FC3F7",
              "#9575CD",
              "#F06292",
              "#7986CB",
              "#FF8A65",
              "#81C784",
              "#4DB6AC"
            ],
      chart: {
        backgroundColor: themeColors.bg,
        style: {
          fontFamily: "Inter, system-ui, sans-serif"
        }
      },
      title: {
        text: "股票K线图",
        style: {
          color: themeColors.text
        }
      },
      subtitle: {
        text: "带技术指标的K线图分析",
        style: {
          color: themeColors.axis
        }
      },
      xAxis: {
        type: "datetime",
        labels: {
          style: {
            color: themeColors.axis
          }
        },
        gridLineColor: themeColors.grid
      },
      yAxis: [
        {
          // title: {
          //   text: '价格',
          //   style: {
          //     color: themeColors.axis
          //   }
          // },
          labels: {
            align: "right",
            x: -3,
            style: {
              color: themeColors.axis
            }
          },
          height: "70%",
          lineWidth: 0, //2
          resize: {
            enabled: true
          },
          gridLineColor: themeColors.grid
        },
        {
          // title: {
          //   text: '成交量',
          //   style: {
          //     color: themeColors.axis
          //   }
          // },
          labels: {
            align: "right",
            x: -3,
            style: {
              color: themeColors.axis
            }
          },
          top: "75%",
          height: "15%",
          offset: 0,
          lineWidth: 0, // 2
          gridLineColor: themeColors.grid
        }
      ],
      tooltip: {
        split: false, // 合并所有系列的提示到一个框中
        backgroundColor: themeColors.tooltipBg,
        borderColor: themeColors.tooltipBorder,
        style: {
          color: themeColors.text
        }
      },
      legend: {
        // 小圆点
        enabled: false,
        itemStyle: {
          color: themeColors.text
        },
        itemHoverStyle: {
          color: "#0EA5E9"
        },
        itemHiddenStyle: {
          color: themeColors.axis
        }
      },

      annotations: [
        {
          type: "fibonacci", // 斐波那契线
          typeOptions: {
            xAxis: 0,
            yAxis: 0,
            points: [
              [new Date("2023-01-01").getTime(), 120],
              [new Date("2023-06-01").getTime(), 180]
            ]
          }
        }
      ],
      navigation: {
        bindings: {
          text: {
            annotationsOptions: {
              labelOptions: {
                verticalAlign: "top",
                y: -11
              }
            }
          }
        }
      },
      navigator: {
        //滚动条
        enabled: false,
        height: 40,
        xAxis: {
          labels: {
            style: {
              color: themeColors.axis
            }
          },
          gridLineColor: themeColors.grid
        },
        maskFill: themeColors.navigatorMask,
        handles: {
          backgroundColor: themeColors.bg,
          borderColor: themeColors.grid
        }
      },
      scrollbar: {
        //一条横线不知道干嘛的
        enabled: false,
        barBackgroundColor: themeColors.scrollbar.bar,
        barBorderRadius: 7,
        barBorderWidth: 0,
        buttonBackgroundColor: themeColors.scrollbar.button,
        buttonBorderColor: themeColors.grid,
        buttonBorderWidth: 1,
        buttonArrowColor: themeColors.axis,
        rifleColor: themeColors.axis,
        trackBackgroundColor: themeColors.scrollbar.track,
        trackBorderColor: themeColors.grid,
        trackBorderWidth: 1,
        trackBorderRadius: 8
      },

      series: []
    };

    return baseOptions;
  }, [theme]);

  // 创建图表
  useEffect(() => {
    if (!chartContainerRef.current) return;

    // 销毁现有图表
    if (chartRef.current) {
      chartRef.current.destroy();
    }

    // 创建新图表
    const options = getChartOptions();

    // 添加蜡烛图系列
    options.series = [
      {
        type: "candlestick",
        name: "价格",
        data: data,
        color: "#EF5350",
        upColor: "#26A69A",
        lineColor: "#B71C1C",
        upLineColor: "#004D40",
        tooltip: {
          valueDecimals: 2
        },
        dataGrouping: {
          units: [
            ["day", [1]],
            ["week", [1]],
            ["month", [1, 3, 6]]
          ]
        }
      },
      {
        type: "column",
        name: "成交量",
        data: data.map(([time, open, high, low, close]) => {
          const volume = Math.floor(Math.random() * 1000000);
          return [time, volume];
        }),
        yAxis: 1,
        color: "#42A5F5",
        dataGrouping: {
          units: [
            ["day", [1]],
            ["week", [1]],
            ["month", [1, 3, 6]]
          ]
        }
      }
    ];

    // 添加技术指标
    if (indicators.includes("sma")) {
      // options.series.push({
      //   type: 'sma',
      //   name: 'SMA 20',
      //   linkedTo: ':previous',
      //   params: {
      //     period: 20
      //   },
      //   zIndex: 1,
      //   color: '#FFB74D'
      // });
    }

    if (indicators.includes("ema")) {
      // options.series.push({
      //   type: 'ema',
      //   name: 'EMA 20',
      //   linkedTo: ':previous',
      //   params: {
      //     period: 20
      //   },
      //   zIndex: 1,
      //   color: '#7E57C2'
      // });
    }

    if (indicators.includes("macd")) {
      // options.series.push({
      //   type: 'macd',
      //   name: 'MACD',
      //   linkedTo: ':previous',
      //   zIndex: 0,
      //   color: '#EC407A'
      // });
    }

    // 创建Highcharts实例
    chartRef.current = Highcharts.stockChart(chartContainerRef.current, options);

    // 清理函数
    return () => {
      if (chartRef.current) {
        chartRef.current.destroy();
        chartRef.current = null;
      }
    };
  }, [chartContainerRef, data, indicators, getChartOptions]);

  // 处理窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      if (chartRef.current) {
        chartRef.current.reflow();
      }
    };

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return (
    <div className={`candlestick-chart ${theme}-theme`}>
      <div className='chart-container'>
        {/* 控制工具栏 */}
        <div className='control-bar'>
          <div className='button-group'>
            <button className='btn-toggle' onClick={refreshData}>
              <i className='fa fa-refresh mr-1'></i> 刷新
            </button>
            <button className='btn-toggle' onClick={toggleTheme}>
              <i className={`fa ${theme === "light" ? "fa-moon-o" : "fa-sun-o"} mr-1`}></i>
              {theme === "light" ? "暗色" : "亮色"}
            </button>
            
          </div>

          <div className='time-range-selector'>
            <span className='label'>时间范围:</span>
            {Object.keys(timeRanges).map(range => (
              <button
                key={range}
                className={`btn-toggle ${timeRange === range ? "active" : ""}`}
                onClick={() => changeTimeRange(range as TimeRange)}
              >
                {range}
              </button>
            ))}
          </div>

          <div className='indicators-selector ml-auto'>
            <span className='label'>技术指标:</span>
            <button
              className={`btn-toggle ${indicators.includes("sma") ? "active" : ""}`}
              onClick={() => toggleIndicator("sma")}
            >
              SMA
            </button>
            <button
              className={`btn-toggle ${indicators.includes("ema") ? "active" : ""}`}
              onClick={() => toggleIndicator("ema")}
            >
              EMA
            </button>
            <button
              className={`btn-toggle ${indicators.includes("macd") ? "active" : ""}`}
              onClick={() => toggleIndicator("macd")}
            >
              MACD
            </button>
          </div>
        </div>
        
        {/* 图表区域 */}
        <div className='chart-wrapper'>
          {isLoading && (
            <div className='loading-overlay'>
              <div className='spinner'></div>
              <p className='loading-text'>加载数据中...</p>
            </div>
          )}
          <div ref={chartContainerRef} className='w-full h-full'></div>
        </div>

        {/* 数据统计区域 */}
        <div className='stats-section'>
          <div className='stats-grid'>
            <div className='stat-card'>
              <p className='stat-title'>当前价格</p>
              <p className='stat-value text-primary'>¥{data[data.length - 1][4].toFixed(2)}</p>
            </div>
            <div className='stat-card'>
              <p className='stat-title'>今日涨跌</p>
              <p className='stat-value text-success'>+¥2.34 (2.4%)</p>
            </div>
            <div className='stat-card'>
              <p className='stat-title'>最高价</p>
              <p className='stat-value'>¥{data[data.length - 1][2].toFixed(2)}</p>
            </div>
            <div className='stat-card'>
              <p className='stat-title'>最低价</p>
              <p className='stat-value'>¥{data[data.length - 1][3].toFixed(2)}</p>
            </div>
          </div>
        </div>

      </div>
    </div>
  );
};

export default CandlestickChart;
